package com.zhentao.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationPlusRequest;
import com.aliyun.green20220302.models.TextModerationPlusResponse;
import com.aliyun.green20220302.models.TextModerationPlusResponseBody;
import com.aliyun.teaopenapi.models.Config;

import java.util.List;


public class TextModerationPlusDemo {

    public static Result textModerationPlus(String content) throws Exception {
        Config config = new Config();
        /**
         * 阿里云账号AccessKey拥有所有API的访问权限，建议您使用RAM用户进行API访问或日常运维。
         * 常见获取环境变量方式：
         * 方式一：
         *     获取RAM用户AccessKey ID：System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     获取RAM用户AccessKey Secret：System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * 方式二：
         *     获取RAM用户AccessKey ID：System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     获取RAM用户AccessKey Secret：System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        config.setAccessKeyId("LTAI5tGVJ7cxtJenkUYMat7V");
        config.setAccessKeySecret("MmZsIc94i6LpJdPJYLKHtNnVI1H66l");
        //接入区域和地址请根据实际情况修改
        config.setRegionId("cn-shanghai");
        config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
        //读取时超时时间，单位毫秒（ms）。
        config.setReadTimeout(6000);
        //连接时超时时间，单位毫秒（ms）。
        config.setConnectTimeout(3000);
        //设置http代理。
        //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
        //设置https代理。
        //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx");
        Client client = new Client(config);

        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", content);

        TextModerationPlusRequest textModerationPlusRequest = new TextModerationPlusRequest();
        // 检测类型
        textModerationPlusRequest.setService("llm_query_moderation");
        textModerationPlusRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            TextModerationPlusResponse response = client.textModerationPlus(textModerationPlusRequest);
            if (response.getStatusCode() == 200) {
                TextModerationPlusResponseBody result = response.getBody();
                System.out.println(JSON.toJSONString(result));
                System.out.println("requestId = " + result.getRequestId());
                System.out.println("code = " + result.getCode());
                System.out.println("msg = " + result.getMessage());
                Integer code = result.getCode();
                if (200 == code) {
                    TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data = result.getData();
                    System.out.println(JSON.toJSONString(data, true));
                    String string = JSON.toJSONString(data, true);
                    //转换JSON对象
                    JSONObject jsonObject = JSONObject.parseObject(string);
                    String riskLevel = (String) jsonObject.get("riskLevel");
                    if (riskLevel.equals("high")){
                        return Result.ERROR1("风险高",400);
                    }

                } else {
                    System.out.println("text moderation not success. code:" + code);
                }
            } else {
                System.out.println("response not success. status:" + response.getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK1("风险低",200);
    }
}
    /*
     * 将同步到es中
     * */
    //查询数据
//    List<Ingredients> ingredients = ingredientsMapper.selectList(null);
//    //创建es索引
//    BulkRequest bulkRequest=new BulkRequest("ingredient");
//        for (Ingredients i:ingredients){
//                Ingredients newIngredient=new Ingredients();
//                BeanUtils.copyProperties(i,newIngredient);
//                String json = JSON.toJSONString(newIngredient);
//                //创建文档
//                IndexRequest indexRequest=new IndexRequest()
//                .id(newIngredient.getIid()+"")
//                .source(json, XContentType.JSON);
//                bulkRequest.add(indexRequest);
//                }
//                client.bulk(bulkRequest, RequestOptions.DEFAULT);
//
//                //es查询数据
//                SearchRequest searchRequest=new SearchRequest("ingredient");
//                SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
//                JSONObject jsonObject = JSON.parseObject(search.toString());
//
//
//                //添加mongodb
//                IngredientSearch ingredientSearch=new IngredientSearch();
//                ingredientSearch.setCreateTimes(new Date());
//
//                Query query=new Query();
//                List<IngredientSearch> ingredientSearches = mongoTemplate.find(query, IngredientSearch.class);
//        if (ingredientSearches.size()<10){
//        mongoTemplate.save(ingredientSearch);
//        }else {
//        return Result.ERROR("mongodb数据大于10",null);
//        }
//        return Result.OK("添加es并查询es",jsonObject);
